module ApplicationHelper
  def link_to_add_fields(name, f, association)
    new_object = f.object.send(association).klass.new
    id = new_object.object_id
    fields = f.fields_for(association, new_object, child_index: id) do |builder|
      render(association.to_s.singularize + "_fields", f: builder)
    end
    link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")})
  end
  
  def decimal_to_Yuan(number)
    output = ""
    # split the number into precision and scale
    d = number.to_s.split(".")    
        
    # process precision
    precision = d[0].split("")
    position = 1
    precision.each do |n|     
 
      # output = output + convert_digit_to_Chinese(n.to_i,position,precision.size) if n != "0"
      output = output + convert_digit_to_Chinese(n.to_i,position,precision.size)       
      position +=1

    end
    output = output + "圆"
        
    #process points
    scale = d[1].split("")
    p = 0
    scale.each do |s|
      output = output + convert_points_to_Chinese(s.to_i, p)
      p += 1
    end
    
    
    # if ( d[1][1] == "0" || d[1][1] == "")  
      # if (d[1][0] == "0" || d[1][0] == "")
        # output = output + "整"
      # else
        # output = output + convert_digit_to_Chinese(d[1][0].to_i,0,0)+"角"
      # end 
    # else       
      # output = output + convert_digit_to_Chinese(d[1][0].to_i,0,0)+"角"+convert_digit_to_Chinese(d[1][1].to_i,0,0)+"分" 
    # end 
    
    return output 
  end
  
  def convert_digit_to_Chinese(digit,position,size)    
    
    # puts "digits: "+ digit.to_s + "   position :"+ position.to_s + "  size: " + size.to_s
        
     digits = ["零","壹","贰","叁","肆","伍","陆","柒","捌","玖"]
     positions = ["仟","","拾","佰"]
     steps = ["","万","亿"]
     
     output = ""
     # index = size - position,  reverse index of array of digits
     # e.g. 12345678,  reverse index is 8,7,6,5,4,3,2,1 
     # position: 8,7,6,5,4,3,2,1
     # mod:      0,3,2,1,0,3,2,1
     # array:    0，1，2，3
     #           仟，佰，拾，个
     
     index = size - position + 1      
     step,mod = index.divmod(4)
             
     # output =  size - position > 0 ?  digits[digit] + positions[size-position-1] : digits[digit]
     if ( size - position > 0 )              
        output = digits[digit] + positions[index%4] if digit > 0
               
        if ( mod == 1 )           
          output = output + steps[step]
        end       
     else
      output = digits[digit] if digit > 0
     end
        
     return output
  end
  
  def convert_points_to_Chinese(digit,position)  
     digits = ["零","壹","贰","叁","肆","伍","陆","柒","捌","玖"]
     positions = ["角","分"]
           
     output =  digit != 0 ?  digits[digit] + positions[position] : ""      
  end
  
end
